<template>
  <div class="login-container">
    <div class="login-form">
      <h2>管理员登录</h2>
      <el-form ref="loginFormRef" :model="loginForm" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { authService } from '../api/authService';

const router = useRouter();
const loading = ref(false);
const loginFormRef = ref();

const loginForm = reactive({
  username: '',
  password: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
};

const handleLogin = async () => {
  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        const response = await authService.login(loginForm);
        
        if (response.code === 200 && response.data.user.role === 'admin') {
          localStorage.setItem('token', response.data.token);
          localStorage.setItem('user', JSON.stringify(response.data.user));
          ElMessage.success('登录成功');
          router.push('/dashboard');
        } else {
          ElMessage.error('非管理员账户禁止登录');
        }
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '登录失败，请检查用户名和密码');
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1a1a1a;
}

.login-form {
  width: 400px;
  padding: 40px;
  background-color: #2a2a2a;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.login-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #ffffff;
}

.el-form-item__label {
  color: #cccccc;
}

.el-input__wrapper {
  background-color: #3a3a3a;
  border-color: #4a4a4a;
}

.el-input__wrapper:hover {
  border-color: #6a6a6a;
}

.el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px #409eff inset;
  border-color: #409eff;
}

.el-input__inner {
  color: #ffffff;
}
</style>